<template>
  <el-card class="app-container">
    <div>
      <div class="itemTitle">隐患上报</div>
      <div class="search">
        <el-form :inline="true" :model="queryParams" ref="queryForm">
          <el-col :span="5">
            <el-form-item label="隐患名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入隐患名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">搜索</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </div>
      <div class="content">
        <div class="ct-btns">
          <el-button type="primary" @click="()=>handleAdd('normal')" v-hasPermi="['risk:danger:add']">新增</el-button>
          <el-button type="primary" @click="()=>handleAdd('leader')" v-hasPermi="['risk:danger:addLeader']">新增</el-button>
        </div>
        <div class="ct-table">
          <elTables :table-data="tableData" :columns="tableColumns" :totalLength="total" :currentPage="queryParams.pageNum"
            :handle-current-change="handleCurrentChange" isPagin :curHeight="tableHeight" />
        </div>
      </div>
    </div>
    <!-- 添加或修改隐患上报对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body @close="cancel" class="dialog-form">
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-col :span="12">
          <el-form-item label="隐患名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入隐患名称" :readonly="!isEdit" :disabled="!isEdit" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车间" prop="shopId">
            <el-select filterable v-model="form.shopId" placeholder="请选择车间" clearable @change="handleShopChange" :readonly="!isEdit" :disabled="!isEdit">
              <el-option v-for="(dict, index) in listShop" :key="index" :label="dict.name" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工房" prop="shopRoomId">
            <el-select filterable v-model="form.shopRoomId" placeholder="请选择工房" clearable :readonly="!isEdit" :disabled="!isEdit">
              <el-option v-for="(dict, index) in listRoom" :key="index" :label="dict.name" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="type=='leader' || form.level">
          <el-form-item label="隐患等级" prop="level">
            <el-select filterable v-model="form.level" placeholder="请选择隐患等级" clearable :readonly="!isEdit" :disabled="!isEdit">
              <el-option v-for="(dict, index) in dangerOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="隐患描述" prop="desc">
            <el-input v-model="form.desc" type="textarea" rows="3" placeholder="请输入内容" :readonly="!isEdit"
              :disabled="!isEdit" maxlength="300" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="隐患图片" prop="imgUrl">
            <elUploads :disabled="!isEdit" :ref="'upload'" :action="action" :auto-upload="true" :limit="5"
            :fileList="fileList" :remove-file="removeFile" :accept="'.jpg,.png'" :success-fun="success"
            :readonly="!isEdit"
            tip="提示：仅允许上传.jpg,.png格式文件，且不能超过100M！">
            </elUploads>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="isEdit">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
const defaultQueryParams = {
  pageNum: 1,
  pageSize: 10,
};
import { pageDanger,getDanger, delDanger, addDanger, updateDanger, exportDanger, downImportTemplate } from "@/api/risk/danger";
import { listRoom, listShop } from "@/api/video/monitor";
export default {
  name: "Danger",
  data() {
    return {
      type:'',
      dangerOptions:[],
      tableHeight: 0,
      isEdit: false,
      dialogFormVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      action: process.env.VUE_APP_BASE_API + "/common/upload",
      tableData: [],
      // 查询参数
      queryParams: {
        ...defaultQueryParams,

        name: null,
        factoryId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "隐患名称不能为空", trigger: "blur" }
        ],
        desc: [
          { required: true, message: "隐患描述不能为空", trigger: "blur" }
        ],
        shopId: [
          { required: true, message: "车间不能为空", trigger: "change" }
        ],
        shopRoomId: [
          { required: true, message: "工房不能为空", trigger: "change" }
        ],
        imgUrl: [
          { required: false, message: "隐患图片不能为空",trigger: "blur" }
        ],
        level: [
          { required: true, message: "隐患等级不能为空", trigger: "change" }
        ],
      },
      tableColumns: [
        { key: "name", title: "隐患名称" },
        { key: "desc", title: "隐患描述" },
        { key: "shopName", title: "车间" },
        { key: "shopRoomName", title: "工房" },
        {
          title: "操作",
          align: "center",
          fixed: 'right',
          width: 200,
          render: (h, params) => {
            return h("div", [
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["risk:danger:info"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleUpdate(params.row, 2)
                    },
                  },
                },
                "查看"
              ),
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                    disabled:params.row.status!=1,
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["risk:danger:edit"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleUpdate(params.row, 1);
                    },
                  },
                },
                "编辑"
              ),
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                    disabled:params.row.status!=1,
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["risk:danger:remove"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleDelete(params.row)
                    },
                  },
                },
                "删除"
              ),
            ]);
          },
        },
      ],
      listRoom: [],
      listShop: [],
      fileList: [],
    };
  },
  created() {
    this.getPage();
  },
  mounted() {
    this.$nextTick(() => {
      this.getTableHeight();
    })
  },
  methods: {
    handleExceed(files, fileList) {
      this.$message.error(`只允许上传单个文件`);
    },
    // 移除文件
    removeFile(file, fileList) {
      this.fileList = fileList;
    },
    // 上传文件
    success(response, file, fileList) {
      if (response.code == 200) {
        this.fileList=fileList;
        this.$message.success("上传成功！");
      }
    },
    handleShopChange(val) {
      delete this.form.shopRoomId;
      console.log('change.val', val);
      this.getlistRoom(val);
    },
    //获取工房
    getlistRoom(val) {
      let params = { workShopId: val };
      listRoom(params).then((res) => {
        this.listRoom = res.data;
      });
    },
    //获取车间
    getlistShop() {
      listShop().then((res) => {
        this.listShop = res.data;
      });
    },
    getTableHeight() {
      let height = document.getElementsByClassName('ct-table')[0].clientHeight;
      this.tableHeight = height - 40;
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getPage();
    },
    /** 查询隐患上报列表 */
    getPage() {
      this.loading = true;
      pageDanger(this.queryParams).then(response => {
        this.tableData = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.fileList=[];
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        shopId: null,
        shopRoomId: null,
        desc: null,
        imgUrl: null,
        status: "0",
        isDanger: null,
        level: null,
        rectifyType: null,
        rectifyTime: null,
        rectifyAsk: null,
        factoryId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        createDept: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getPage();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(type) {
      this.type=type;
      if(type=='leader'){
        this.getDicts('danger_level').then(response => {
          this.dangerOptions=response.data;
        });
      }
      this.reset();
      this.open = true;
      this.isEdit = true;
      this.title = "新增隐患上报";
      this.getlistShop();
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      this.getlistShop();
      this.getDicts('danger_level').then(response => {
        this.dangerOptions=response.data;
      });
      if (type == 1) {
        this.isEdit = true;
        this.title = "编辑隐患上报";
      } else {
        this.isEdit = false;
        this.title = "查看隐患上报";
      }
      this.reset();
      const id = row.id || this.ids
      getDanger(id).then(response => {
        this.form = response.data;
        this.fileList=this.form.imgUrl?JSON.parse(this.form.imgUrl):[];
        this.open = true;
        this.getlistRoom(this.form.shopId); 
      });
    },
    /** 提交按钮 */
    submitForm() {
      // 对imgUrl处理
      if(this.fileList&&this.fileList.length>0){
        let ls=this.fileList.map(_ => {
          return {
            url:_?.response?.fileName??_.url,
            name:_?.response?.oldFileName??_.name,
          }
        })
        this.form.imgUrl=JSON.stringify(ls);
      }else{
        this.form.imgUrl='';
      }

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDanger(this.form).then(response => {
              this.fileList=[];
              this.msgSuccess("修改成功");
              this.$refs.upload.$refs.uploadRef.clearFiles();
              this.open = false;
              this.getPage();
            });
          } else {
            addDanger(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.fileList=[];
              this.$refs.upload.$refs.uploadRef.clearFiles();
              this.open = false;
              this.getPage();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除该隐患上报', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        let data
        if (Array.isArray(ids)) {
          data = ids
        } else {
          data = [ids]
        }
        return delDanger(data);
      }).then(() => {
        this.getPage();
        this.msgSuccess("删除成功");
      })
    },
  }
};
</script>
<style lang="scss" scoped></style>